package com.example.thegreatwall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.thegreatwall.common.R;
import com.example.thegreatwall.common.api.CommonResult;
import com.example.thegreatwall.entity.Comment;
import com.example.thegreatwall.entity.TProduct;
import com.example.thegreatwall.service.CommentService;
import com.example.thegreatwall.service.OrderService;
import com.example.thegreatwall.service.TProductService;
import org.apache.ibatis.annotations.Param;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 套餐商品控制器
 * 处理套餐商品的基本信息，包括列表查询、详情查看、分类查询和搜索功能
 */
@RestController
@RequestMapping("/tproduct")
@CrossOrigin(origins = "*")
public class TProductController {

    @Autowired
    private TProductService tProductService;
    @Autowired
    private CommentService commentService;

    /**
     * 查询套餐
     * @param level 热门等级
     * @return 套餐集合
     */
    @GetMapping("/getTProductByLevel")
    public R getTProductByLevel(@Param("level") Integer level){
        QueryWrapper<TProduct> queryWrapper = new QueryWrapper<>();
        if (level!=null){
            queryWrapper.eq("hot_level",level);
            queryWrapper.eq("status",1); //状态为正常的商品
            queryWrapper.orderByDesc("countnum");
        }
        return new R().addDate("list",tProductService.list(queryWrapper));
    }

    @GetMapping("/getTProductById")
    public R getTProductById(@Param("id") Integer id){
        TProduct tProduct = tProductService.getById(id);
        //计算这个商品评分
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",id);
        queryWrapper.eq("product_type",1);

        List<Comment> comments = commentService.list(queryWrapper);
        BigDecimal num=new BigDecimal(0);
        for (Comment comment : comments) {
//            System.out.println(comment.getScore());
            num=num.add(comment.getScore());
        }
        // 1 表示保留 1 位小数，ROUND_HALF_UP 是四舍五入模式
        BigDecimal num2=new BigDecimal(comments.size());
        if (comments.size()>0){
            tProduct.setScore(num.divide(num2,2,BigDecimal.ROUND_HALF_UP));
        }

        System.out.println("这是我算出的分数："+tProduct.getScore());
        QueryWrapper<TProduct> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("t_product_id",id);
        boolean update = tProductService.update(tProduct,queryWrapper1);
        return new R().addDate("product",tProduct);
    }

    /**
     * 获取套餐列表
     * 支持分页查询、按套餐类型筛选和关键词搜索
     *
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @param packageType 套餐类型，可选参数
     * @param keyword 搜索关键词，可选参数
     * @return 返回分页的套餐列表数据
     */
    @GetMapping("/list")
    public CommonResult<Page<TProduct>> listTProducts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
            @RequestParam(value = "packageType", required = false) Integer packageType,
            @RequestParam(value = "keyword", required = false) String keyword) {

        Page<TProduct> productList;
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有关键词，执行搜索
            productList = tProductService.searchTProducts(keyword, pageNum, pageSize);
        } else {
            // 否则按类型查询
            productList = tProductService.listTProducts(pageNum, pageSize, packageType);
        }
        return CommonResult.success(productList);
    }

    /**
     * 获取套餐详情
     * 根据套餐ID获取单个套餐的详细信息
     *
     * @param tProductId 套餐ID
     * @return 返回套餐详细信息
     */
    @GetMapping("/detail/{tProductId}")
    public CommonResult<TProduct> getTProductDetail(@PathVariable Integer tProductId) {
        TProduct product = tProductService.getTProductDetail(tProductId);
        return CommonResult.success(product);
    }

    /**
     * 按类型获取套餐列表
     * 根据套餐类型获取对应的套餐列表
     *
     * @param packageType 套餐类型
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @return 返回分页的套餐列表数据
     */
    @GetMapping("/type/{packageType}")
    public CommonResult<Page<TProduct>> getTProductsByType(
            @PathVariable Integer packageType,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Page<TProduct> productList = tProductService.getTProductsByType(packageType, pageNum, pageSize);
        return CommonResult.success(productList);
    }

    /**
     * 搜索套餐
     * 根据关键词搜索套餐名称和描述
     *
     * @param keyword 搜索关键词
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @return 返回分页的搜索结果
     */
    @GetMapping("/search")
    public CommonResult<Page<TProduct>> searchTProducts(
            @RequestParam String keyword,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Page<TProduct> searchResult = tProductService.searchTProducts(keyword, pageNum, pageSize);
        return CommonResult.success(searchResult);
    }

    /**
     * 获取热门套餐
     * 获取热门等级大于0的套餐列表，按热门等级、评分和创建时间排序
     *
     * @param pageNum 当前页码，默认1
     * @param pageSize 每页数量，默认20
     * @return 返回分页的热门套餐列表
     */
    @GetMapping("/hot")
    public CommonResult<Page<TProduct>> getHotTProducts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        Page<TProduct> hotProducts = tProductService.getHotTProducts(pageNum, pageSize);
        return CommonResult.success(hotProducts);
    }

    @GetMapping(value = "updhot")
    public int updhot(){
        tProductService.update(
                new UpdateWrapper<TProduct>()
                        .set("hot_level", 2)
                        .ge("countnum", 10000)
        );
        return 1;
    }

}